<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="PLM文件数据展示系统 - 用于管理和查看产品生命周期管理数据">
    <title>PLM文件数据展示系统 - 合并日志视图</title>

    <!-- 基础样式 -->
    <style>
        :root {
            /* 颜色系统 */
            --primary-color: #3498db;
            --primary-light: #5dade2;
            --primary-dark: #2980b9;
            --secondary-color: #2ecc71;
            --secondary-light: #58d68d;
            --secondary-dark: #27ae60;
            --danger-color: #e74c3c;
            --danger-light: #ec7063;
            --danger-dark: #c0392b;
            --warning-color: #f39c12;
            --warning-light: #f5b041;
            --warning-dark: #d35400;
            --dark-color: #2c3e50;
            --light-color: #ecf0f1;
            --white: #ffffff;
            --shadow: rgba(0, 0, 0, 0.1);

            /* 尺寸系统 */
            --border-radius: 6px;
            --border-radius-sm: 4px;
            --border-radius-lg: 8px;
            --box-shadow: 0 2px 8px var(--shadow);
            --transition: all 0.2s ease;

            /* 间距系统 */
            --spacing-xs: 3px;
            --spacing-sm: 6px;
            --spacing-md: 12px;
            --spacing-lg: 18px;
            --spacing-xl: 24px;

            /* 字体系统 */
            --font-size-xs: 11px;
            --font-size-sm: 13px;
            --font-size-md: 15px;
            --font-size-lg: 17px;
            --font-size-xl: 20px;

            /* 布局系统 */
            --container-width: 95vw;
            --header-height: 60px;
        }

        /* 基础重置 */
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: #f5f7fa;
            color: var(--dark-color);
            line-height: 1.5;
            font-size: var(--font-size-md);
        }

        /* 容器布局 */
        .container {
            max-width: var(--container-width);
            margin: 0 auto;
            padding: var(--spacing-md);
        }

        /* 头部样式 */
        header {
            background: linear-gradient(135deg, var(--primary-color), var(--primary-light));
            color: var(--white);
            padding: var(--spacing-md) 0;
            margin-bottom: var(--spacing-lg);
            border-radius: var(--border-radius);
            box-shadow: var(--box-shadow);
            height: var(--header-height);
            display: flex;
            align-items: center;
            justify-content: center;
        }

        header h1 {
            font-size: var(--font-size-xl);
            font-weight: 300;
            letter-spacing: 1px;
            display: flex;
            align-items: center;
            gap: var(--spacing-sm);
        }

        /* 主内容区布局 */
        .main-content {
            width: 100%;
        }

        /* 内容区域样式 */
        .content {
            background-color: var(--white);
            border-radius: var(--border-radius);
            box-shadow: var(--box-shadow);
            padding: var(--spacing-md);
        }

        /* 工具栏样式 */
        .toolbar {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: var(--spacing-lg);
            flex-wrap: wrap;
            gap: var(--spacing-sm);
        }

        .toolbar-left {
            display: flex;
            gap: var(--spacing-sm);
            flex-wrap: wrap;
        }

        /* 按钮样式 */
        .btn {
            background-color: var(--primary-color);
            color: var(--white);
            border: none;
            padding: var(--spacing-sm) var(--spacing-md);
            border-radius: var(--border-radius);
            cursor: pointer;
            font-size: var(--font-size-sm);
            transition: var(--transition);
            display: flex;
            align-items: center;
            gap: var(--spacing-xs);
        }

        .btn:hover {
            background-color: var(--primary-dark);
            transform: translateY(-1px);
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }

        .btn:active {
            transform: translateY(0);
        }

        .btn-secondary {
            background-color: #95a5a6;
        }

        .btn-secondary:hover {
            background-color: #7f8c8d;
        }

        .btn-success {
            background-color: var(--secondary-color);
        }

        .btn-success:hover {
            background-color: var(--secondary-dark);
        }

        .btn-danger {
            background-color: var(--danger-color);
        }

        .btn-danger:hover {
            background-color: var(--danger-dark);
        }

        .btn-warning {
            background-color: var(--warning-color);
        }

        .btn-warning:hover {
            background-color: var(--warning-dark);
        }

        .btn-sm {
            padding: var(--spacing-xs) var(--spacing-sm);
            font-size: var(--font-size-xs);
        }

        /* 当前文件信息样式 */
        .current-file {
            color: #7f8c8d;
            font-size: var(--font-size-sm);
            display: flex;
            align-items: center;
            gap: var(--spacing-xs);
        }

        .current-file strong {
            color: var(--dark-color);
        }

        /* 表格样式 */
        .table-container {
            overflow-x: auto;
            border-radius: var(--border-radius);
            border: 1px solid #e0e0e0;
            margin-bottom: var(--spacing-lg);
        }

        table {
            width: 100%;
            border-collapse: collapse;
        }

        th, td {
            padding: var(--spacing-sm) var(--spacing-md);
            text-align: left;
            border-bottom: 1px solid #e0e0e0;
            font-size: var(--font-size-sm);
            word-wrap: break-word;
            word-break: break-all;
            white-space: normal;
        }

        th {
            background-color: var(--light-color);
            font-weight: 600;
            color: var(--dark-color);
            position: sticky;
            top: 0;
            z-index: 10;
            white-space: nowrap;
        }

        tr:hover {
            background-color: #f8f9fa;
        }

        tr.highlighted {
            background-color: #fff3cd !important;
            color: #856404;
        }

        .checkbox {
            width: 16px;
            height: 16px;
            cursor: pointer;
        }

        /* 分页样式 */
        .pagination {
            display: flex;
            justify-content: center;
            align-items: center;
            margin-top: var(--spacing-lg);
            gap: var(--spacing-xs);
            flex-wrap: wrap;
        }

        .page-info {
            margin: 0 var(--spacing-sm);
            color: #7f8c8d;
            font-size: var(--font-size-sm);
        }

        .page-btn {
            padding: var(--spacing-xs) var(--spacing-sm);
            border: 1px solid #ddd;
            background-color: var(--white);
            cursor: pointer;
            border-radius: var(--border-radius);
            transition: var(--transition);
            font-size: var(--font-size-sm);
        }

        .page-btn:hover {
            background-color: #f0f0f0;
        }

        .page-btn.active {
            background-color: var(--primary-color);
            color: var(--white);
            border-color: var(--primary-color);
        }

        .page-btn:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }

        /* 状态样式 */
        .status-success {
            color: var(--secondary-color);
            font-weight: 500;
        }

        .status-error {
            color: var(--danger-color);
            font-weight: 500;
        }

        /* 加载指示器样式 */
        .loading {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 200px;
        }

        .spinner {
            width: 30px;
            height: 30px;
            border: 3px solid rgba(0, 0, 0, 0.1);
            border-radius: 50%;
            border-top-color: var(--primary-color);
            animation: spin 1s ease-in-out infinite;
        }

        @keyframes spin {
            to { transform: rotate(360deg); }
        }

        /* 空状态样式 */
        .empty-state {
            text-align: center;
            padding: var(--spacing-xl) var(--spacing-md);
            color: #7f8c8d;
        }

        .empty-state i {
            font-size: 36px;
            margin-bottom: var(--spacing-md);
            color: #bdc3c7;
        }

        /* 通知样式 */
        .notification {
            position: fixed;
            top: var(--spacing-md);
            right: var(--spacing-md);
            padding: var(--spacing-sm) var(--spacing-md);
            background-color: var(--white);
            border-radius: var(--border-radius);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
            z-index: 1000;
            display: flex;
            align-items: center;
            gap: var(--spacing-sm);
            transform: translateX(150%);
            transition: transform 0.3s ease;
            max-width: 350px;
        }

        .notification.show {
            transform: translateX(0);
        }

        .notification.success {
            border-left: 4px solid var(--secondary-color);
        }

        .notification.error {
            border-left: 4px solid var(--danger-color);
        }

        .notification.info {
            border-left: 4px solid var(--primary-color);
        }

        .notification.warning {
            border-left: 4px solid var(--warning-color);
        }

        .notification-icon {
            font-size: 18px;
        }

        .notification.success .notification-icon {
            color: var(--secondary-color);
        }

        .notification.error .notification-icon {
            color: var(--danger-color);
        }

        .notification.info .notification-icon {
            color: var(--primary-color);
        }

        .notification.warning .notification-icon {
            color: var(--warning-color);
        }

        .notification-close {
            margin-left: auto;
            cursor: pointer;
            color: #7f8c8d;
        }

        /* 高级筛选面板样式 */
        .advanced-filter {
            background-color: var(--white);
            border-radius: var(--border-radius);
            box-shadow: var(--box-shadow);
            padding: var(--spacing-md);
            margin-bottom: var(--spacing-lg);
            display: none;
        }

        .advanced-filter.show {
            display: block;
            animation: slideDown 0.3s ease;
        }

        @keyframes slideDown {
            from {
                opacity: 0;
                transform: translateY(-20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .filter-row {
            display: flex;
            gap: var(--spacing-md);
            margin-bottom: var(--spacing-md);
            flex-wrap: wrap;
        }

        .filter-col {
            flex: 1;
            min-width: 180px;
        }

        /* 表单样式 */
        .form-group {
            margin-bottom: var(--spacing-md);
        }

        .form-group label {
            display: block;
            margin-bottom: var(--spacing-xs);
            font-weight: 500;
            color: var(--dark-color);
        }

        .form-control {
            width: 100%;
            padding: var(--spacing-sm);
            border: 1px solid #ddd;
            border-radius: var(--border-radius);
            font-size: var(--font-size-sm);
            transition: var(--transition);
        }

        .form-control:focus {
            outline: none;
            border-color: var(--primary-color);
            box-shadow: 0 0 0 2px rgba(52, 152, 219, 0.2);
        }

        /* 模态框样式 */
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            animation: fadeIn 0.3s;
        }

        .modal-content {
            background-color: var(--white);
            margin: 10% auto;
            padding: var(--spacing-md);
            border-radius: var(--border-radius);
            width: 50%;
            max-width: 600px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
            animation: slideIn 0.3s;
        }

        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }

        @keyframes slideIn {
            from { transform: translateY(-50px); opacity: 0; }
            to { transform: translateY(0); opacity: 1; }
        }

        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: var(--spacing-md);
            padding-bottom: var(--spacing-sm);
            border-bottom: 1px solid #eee;
        }

        .modal-header h3 {
            margin: 0;
            color: var(--dark-color);
        }

        .modal-close {
            font-size: 24px;
            cursor: pointer;
            color: #7f8c8d;
        }

        .modal-close:hover {
            color: var(--dark-color);
        }

        .modal-body {
            margin-bottom: var(--spacing-md);
        }

        .modal-footer {
            display: flex;
            justify-content: flex-end;
            gap: var(--spacing-sm);
        }

        /* 工具提示样式 */
        .tooltip {
            position: relative;
            display: inline-block;
        }

        .tooltip .tooltiptext {
            visibility: hidden;
            width: 120px;
            background-color: #555;
            color: var(--white);
            text-align: center;
            border-radius: var(--border-radius-sm);
            padding: var(--spacing-xs);
            position: absolute;
            z-index: 1;
            bottom: 125%;
            left: 50%;
            margin-left: -60px;
            opacity: 0;
            transition: opacity 0.3s;
        }

        .tooltip:hover .tooltiptext {
            visibility: visible;
            opacity: 1;
        }

        /* 响应式布局优化 */
        @media (max-width: 768px) {
            .container {
                padding: var(--spacing-sm);
            }

            header h1 {
                font-size: var(--font-size-lg);
            }

            .toolbar {
                flex-direction: column;
                align-items: flex-start;
            }

            .toolbar-left {
                width: 100%;
                justify-content: space-between;
            }

            .btn {
                padding: var(--spacing-xs) var(--spacing-sm);
                font-size: var(--font-size-xs);
            }

            .current-file {
                font-size: var(--font-size-xs);
                width: 100%;
                justify-content: center;
                margin-top: var(--spacing-sm);
            }

            th, td {
                padding: var(--spacing-xs) var(--spacing-sm);
                font-size: var(--font-size-xs);
            }

            .page-btn {
                padding: var(--spacing-xs) var(--spacing-sm);
                font-size: var(--font-size-xs);
            }

            .page-info {
                font-size: var(--font-size-xs);
                margin: 0 var(--spacing-xs);
            }

            .modal-content {
                width: 90%;
                margin: 20% auto;
            }

            .filter-row {
                flex-direction: column;
            }
        }
    </style>

    <!-- Font Awesome图标库 -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <!-- SheetJS库用于Excel导出 -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
</head>
<body>
<div class="container">
    <header>
        <h1><i class="fas fa-database"></i> PLM文件数据展示系统 - 合并日志视图</h1>
    </header>

    <div class="main-content">
        <main class="content">
            <div class="toolbar">
                <div class="toolbar-left">
                    <button class="btn" onclick="loadAllLogs()">
                        <i class="fas fa-sync-alt"></i> 刷新日志数据
                    </button>
                    <button class="btn btn-success" onclick="exportSelected()">
                        <i class="fas fa-download"></i> 导出选中
                    </button>
                    <button class="btn btn-secondary" onclick="clearSelection()">
                        <i class="fas fa-times"></i> 清除选择
                    </button>
                    <button class="btn btn-warning" onclick="toggleAdvancedFilter()">
                        <i class="fas fa-filter"></i> 高级筛选
                    </button>
                </div>
                <div class="current-file">
                    <i class="fas fa-file-alt"></i> 显示所有日志数据（按时间倒序）
                </div>
            </div>

            <!-- 高级筛选面板 -->
            <div id="advancedFilter" class="advanced-filter">
                <div class="filter-row">
                    <div class="filter-col">
                        <div class="form-group">
                            <label for="filterType">类型</label>
                            <select id="filterType" class="form-control">
                                <option value="">全部</option>
                                <option value="backup">成功</option>
                                <option value="error">失败</option>
                            </select>
                        </div>
                    </div>
                    <div class="filter-col">
                        <div class="form-group">
                            <label for="filterErpCode">ERP编码</label>
                            <input type="text" id="filterErpCode" class="form-control" placeholder="输入ERP编码">
                        </div>
                    </div>
                    <div class="filter-col">
                        <div class="form-group">
                            <label for="filterPartNo">部件编号</label>
                            <input type="text" id="filterPartNo" class="form-control" placeholder="输入部件编号">
                        </div>
                    </div>
                </div>
                <div class="filter-row">
                    <div class="filter-col">
                        <div class="form-group">
                            <label for="filterDateFrom">开始日期</label>
                            <input type="date" id="filterDateFrom" class="form-control">
                        </div>
                    </div>
                    <div class="filter-col">
                        <div class="form-group">
                            <label for="filterDateTo">结束日期</label>
                            <input type="date" id="filterDateTo" class="form-control">
                        </div>
                    </div>
                    <div class="filter-col" style="display: flex; align-items: flex-end;">
                        <button class="btn" onclick="applyAdvancedFilter()">
                            <i class="fas fa-search"></i> 应用筛选
                        </button>
                        <button class="btn btn-secondary" onclick="resetAdvancedFilter()">
                            <i class="fas fa-undo"></i> 重置
                        </button>
                    </div>
                </div>
            </div>

            <!-- 数据表格 -->
            <div class="table-container">
                <table>
                    <thead>
                    <tr>
                        <th style="width: 40px;">
                            <div class="tooltip">
                                <input type="checkbox" id="selectAll" class="checkbox" onchange="toggleSelectAll()">
                                <span class="tooltiptext">全选/取消全选</span>
                            </div>
                        </th>
                        <th onclick="sortTable(0)">文件名 <i class="fas fa-sort"></i></th>
                        <th onclick="sortTable(1)">类型 <i class="fas fa-sort"></i></th>
                        <th onclick="sortTable(2)">ERP编码 <i class="fas fa-sort"></i></th>
                        <th onclick="sortTable(3)">部件编号 <i class="fas fa-sort"></i></th>
                        <th onclick="sortTable(4)">类产品组 <i class="fas fa-sort"></i></th>
                        <th onclick="sortTable(5)">产品组 <i class="fas fa-sort"></i></th>
                        <th onclick="sortTable(6)">子产品组 <i class="fas fa-sort"></i></th>
                        <th onclick="sortTable(7)">部件名称1 <i class="fas fa-sort"></i></th>
                        <th onclick="sortTable(8)">类型号码 <i class="fas fa-sort"></i></th>
                        <th onclick="sortTable(9)">技术参数 <i class="fas fa-sort"></i></th>
                        <th onclick="sortTable(10)">描述 <i class="fas fa-sort"></i></th>
                        <th onclick="sortTable(11)">扫描时间 <i class="fas fa-sort"></i></th>
                        <th>操作</th>
                    </tr>
                    </thead>
                    <tbody id="dataTable"></tbody>
                </table>
                <div id="loadingIndicator" class="loading" style="display: none;">
                    <div class="spinner"></div>
                </div>
                <div id="emptyState" class="empty-state" style="display: none;">
                    <i class="fas fa-inbox"></i>
                    <p>没有可显示的数据</p>
                </div>
            </div>

            <!-- 分页控件 -->
            <div class="pagination" id="pagination"></div>
        </main>
    </div>
</div>

<!-- 详情模态框 -->
<div id="detailModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h3>记录详情</h3>
            <span class="modal-close" onclick="closeDetailModal()">&times;</span>
        </div>
        <div class="modal-body" id="detailContent">
            <!-- 详情内容将在这里动态生成 -->
        </div>
        <div class="modal-footer">
            <button class="btn btn-secondary" onclick="closeDetailModal()">关闭</button>
        </div>
    </div>
</div>

<!-- 导出选项模态框 -->
<div id="exportModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h3>导出选项</h3>
            <span class="modal-close" onclick="closeExportModal()">&times;</span>
        </div>
        <div class="modal-body">
            <div class="form-group">
                <label>导出格式</label>
                <select id="exportFormat" class="form-control">
                    <option value="csv">CSV</option>
                    <option value="excel">Excel</option>
                    <option value="json">JSON</option>
                </select>
            </div>
            <div class="form-group">
                <label>
                    <input type="checkbox" id="exportAllColumns" checked> 导出所有列
                </label>
            </div>
            <div class="form-group">
                <label>
                    <input type="checkbox" id="exportSelectedOnly" checked> 仅导出选中的记录
                </label>
            </div>
        </div>
        <div class="modal-footer">
            <button class="btn btn-secondary" onclick="closeExportModal()">取消</button>
            <button class="btn btn-success" onclick="confirmExport()">确认导出</button>
        </div>
    </div>
</div>

<!-- 通知 -->
<div id="notification" class="notification">
    <i class="fas fa-info-circle notification-icon"></i>
    <span id="notificationMessage"></span>
    <span class="notification-close" onclick="closeNotification()">&times;</span>
</div>

<script>
    // 全局变量
    let currentPage = 1;
    const itemsPerPage = 1000;
    let currentFileName = "all_logs";
    let allData = [];
    let filteredData = [];
    let selectedKeys = [];
    let sortColumn = -1;
    let sortDirection = 1; // 1: 升序, -1: 降序
    let autoRefreshInterval = null;

    // 初始化
    document.addEventListener('DOMContentLoaded', function() {
        // 直接加载所有日志数据
        loadAllLogs();

        // 设置自动刷新
        setupAutoRefresh();
    });

    // 设置自动刷新
    function setupAutoRefresh() {
        // 默认每5分钟刷新一次所有日志数据
        autoRefreshInterval = setInterval(() => {
            if (document.visibilityState === 'visible') {
                loadAllLogs();
            }
        }, 5 * 60 * 1000);
    }

    // 显示通知
    function showNotification(message, type = 'info') {
        const notification = document.getElementById('notification');
        const messageElement = document.getElementById('notificationMessage');
        const iconElement = notification.querySelector('.notification-icon');

        // 设置图标
        if (type === 'success') {
            iconElement.className = 'fas fa-check-circle notification-icon';
        } else if (type === 'error') {
            iconElement.className = 'fas fa-exclamation-circle notification-icon';
        } else if (type === 'warning') {
            iconElement.className = 'fas fa-exclamation-triangle notification-icon';
        } else {
            iconElement.className = 'fas fa-info-circle notification-icon';
        }

        messageElement.textContent = message;
        notification.className = 'notification show ' + type;

        // 自动关闭通知
        setTimeout(() => {
            notification.classList.remove('show');
        }, 5000);
    }

    // 关闭通知
    function closeNotification() {
        document.getElementById('notification').classList.remove('show');
    }

    // 获取选中行的键
    function getSelectedKeysKey(fileName) {
        return 'selectedRows_' + fileName;
    }

    // 保存选中行
    function saveSelectedRows(fileName, selectedKeys) {
        localStorage.setItem(getSelectedKeysKey(fileName), JSON.stringify(selectedKeys));
    }

    // 加载选中行
    function loadSelectedRows(fileName) {
        const data = localStorage.getItem(getSelectedKeysKey(fileName));
        return data ? JSON.parse(data) : [];
    }

    // 格式化日期时间
    function formatToChineseDatetime(str) {
        if (!str || str.indexOf(' ') === -1) return str;
        const months = {
            Jan: '01', Feb: '02', Mar: '03', Apr: '04', May: '05', Jun: '06',
            Jul: '07', Aug: '08', Sep: '09', Oct: '10', Nov: '11', Dec: '12'
        };
        const parts = str.split(' ');
        if (parts.length < 6) return str;
        const year = parts[5];
        const month = months[parts[1]];
        const day = parts[2];
        const time = parts[3];
        return `${year}-${month}-${day} ${time}`;
    }

    // 加载所有日志数据（合并显示）
    function loadAllLogs() {
        showLoading(true);
        currentPage = 1;

        fetch('/api/plmfile/alllogs')
            .then(res => {
                if (!res.ok) {
                    throw new Error('网络响应异常');
                }
                return res.json();
            })
            .then(lines => {
                allData = lines;
                filteredData = [...allData];
                
                // 默认按时间倒序排序（最新的在前）
                sortColumn = 11;
                sortDirection = -1;
                filteredData.sort((a, b) => {
                    const aCols = a.split(" < /dev/null | ");
                    const bCols = b.split("|");
                    const aDateStr = formatToChineseDatetime(aCols[11]);
                    const bDateStr = formatToChineseDatetime(bCols[11]);
                    const aDate = new Date(aDateStr);
                    const bDate = new Date(bDateStr);
                    return sortDirection * (aDate - bDate);
                });
                
                // 更新排序图标
                document.querySelectorAll("th i").forEach(icon => {
                    icon.className = "fas fa-sort";
                });
                const timeIcon = document.querySelectorAll("th")[12].querySelector("i");
                timeIcon.className = "fas fa-sort-down";
                
                renderTable();
                renderPagination();
                showLoading(false);
                showNotification(`已加载 ${lines.length} 条日志记录`, "success");
            })
            .catch(err => {
                console.error('加载日志失败:', err);
                showLoading(false);
                alert('加载日志失败: ' + err.message);
            });
    }

    // 渲染表格
    function renderTable() {
        const tbody = document.getElementById('dataTable');
        tbody.innerHTML = '';

        if (filteredData.length === 0) {
            document.getElementById('emptyState').style.display = 'block';
            return;
        }

        document.getElementById('emptyState').style.display = 'none';

        const startIndex = (currentPage - 1) * itemsPerPage;
        const endIndex = Math.min(startIndex + itemsPerPage, filteredData.length);
        const pageData = filteredData.slice(startIndex, endIndex);

        selectedKeys = loadSelectedRows(currentFileName);

        // 使用文档片段提高性能
        const fragment = document.createDocumentFragment();

        pageData.forEach((line, index) => {
            const cols = line.split('|');

            // 类型字段转换
            if (cols[1] === 'backup') {
                cols[1] = '<span class="status-success">成功</span>';
            } else if (cols[1] === 'error') {
                cols[1] = '<span class="status-error">失败</span>';
            }

            // 时间字段转换
            const timeIdx = cols.length - 1;
            cols[timeIdx] = formatToChineseDatetime(cols[timeIdx]);

            const tr = document.createElement('tr');
            const rowKey = cols[2] + '_' + cols[3];
            const globalIndex = startIndex + index;

            // 创建复选框
            const checkbox = document.createElement('input');
            checkbox.type = 'checkbox';
            checkbox.className = 'checkbox';
            checkbox.dataset.key = rowKey;
            checkbox.dataset.index = globalIndex;

            if (selectedKeys.includes(rowKey)) {
                checkbox.checked = true;
                tr.classList.add('highlighted');
            }

            checkbox.onclick = function(e) {
                e.stopPropagation();
                updateRowSelection(tr, checkbox, rowKey);
            };

            const tdCheckbox = document.createElement('td');
            tdCheckbox.appendChild(checkbox);
            tr.appendChild(tdCheckbox);

            // 添加其他列
            cols.forEach((col, colIndex) => {
                const td = document.createElement('td');
                td.innerHTML = col;

                // 为长文本列设置最大宽度和自动换行
                if ([7, 9, 10].includes(colIndex)) {
                    td.style.maxWidth = '200px';
                    td.style.wordWrap = 'break-word';
                    td.style.wordBreak = 'break-all';
                    td.style.whiteSpace = 'normal';
                }

                tr.appendChild(td);
            });

            // 添加操作列
            const actionTd = document.createElement('td');
            actionTd.innerHTML = `
                    <button class="btn btn-secondary btn-sm" onclick="showDetail(${globalIndex})">
                        <i class="fas fa-eye"></i>
                    </button>
                `;
            tr.appendChild(actionTd);

            // 行点击事件
            tr.onclick = function(e) {
                if (e.target.type === 'checkbox' || e.target.tagName === 'BUTTON' || e.target.tagName === 'I') return;
                checkbox.checked = !checkbox.checked;
                updateRowSelection(tr, checkbox, rowKey);
            };

            fragment.appendChild(tr);
        });

        tbody.appendChild(fragment);
    }

    // 更新行选择状态
    function updateRowSelection(tr, checkbox, rowKey) {
        if (checkbox.checked) {
            tr.classList.add('highlighted');
            if (!selectedKeys.includes(rowKey)) {
                selectedKeys.push(rowKey);
            }
        } else {
            tr.classList.remove('highlighted');
            selectedKeys = selectedKeys.filter(k => k !== rowKey);
        }

        saveSelectedRows(currentFileName, selectedKeys);
        updateSelectAllCheckbox();
    }

    // 全选/取消全选
    function toggleSelectAll() {
        const selectAll = document.getElementById('selectAll');
        const checkboxes = document.querySelectorAll('#dataTable input[type="checkbox"]:not(#selectAll)');

        if (selectAll.checked) {
            checkboxes.forEach(checkbox => {
                checkbox.checked = true;
                checkbox.closest('tr').classList.add('highlighted');
                const rowKey = checkbox.dataset.key;
                if (!selectedKeys.includes(rowKey)) {
                    selectedKeys.push(rowKey);
                }
            });
        } else {
            checkboxes.forEach(checkbox => {
                checkbox.checked = false;
                checkbox.closest('tr').classList.remove('highlighted');
            });
            selectedKeys = [];
        }

        saveSelectedRows(currentFileName, selectedKeys);
    }

    // 更新全选复选框状态
    function updateSelectAllCheckbox() {
        const selectAll = document.getElementById('selectAll');
        const checkboxes = document.querySelectorAll('#dataTable input[type="checkbox"]:not(#selectAll)');
        const checkedBoxes = document.querySelectorAll('#dataTable input[type="checkbox"]:not(#selectAll):checked');

        if (checkboxes.length === 0) {
            selectAll.checked = false;
            selectAll.indeterminate = false;
        } else if (checkedBoxes.length === checkboxes.length) {
            selectAll.checked = true;
            selectAll.indeterminate = false;
        } else {
            selectAll.checked = false;
            selectAll.indeterminate = true;
        }
    }

    // 表格排序
    function sortTable(columnIndex) {
        // 如果点击同一列，则切换排序方向
        if (sortColumn === columnIndex) {
            sortDirection *= -1;
        } else {
            sortColumn = columnIndex;
            sortDirection = 1; // 默认升序
        }

        // 更新排序图标
        document.querySelectorAll('th i').forEach(icon => {
            icon.className = 'fas fa-sort';
        });

        const currentIcon = document.querySelectorAll('th')[columnIndex + 1].querySelector('i');
        if (sortDirection === 1) {
            currentIcon.className = 'fas fa-sort-up';
        } else {
            currentIcon.className = 'fas fa-sort-down';
        }

        // 执行排序
        filteredData.sort((a, b) => {
            const aCols = a.split('|');
            const bCols = b.split('|');

            // 特殊处理时间列
            if (columnIndex === 11) {
                // 先转换为标准日期格式再比较
                const aDateStr = formatToChineseDatetime(aCols[columnIndex]);
                const bDateStr = formatToChineseDatetime(bCols[columnIndex]);
                const aDate = new Date(aDateStr);
                const bDate = new Date(bDateStr);
                return sortDirection * (aDate - bDate);
            }

            // 特殊处理数字列
            if ([2, 3, 8].includes(columnIndex)) {
                const aNum = parseFloat(aCols[columnIndex]) || 0;
                const bNum = parseFloat(bCols[columnIndex]) || 0;
                return sortDirection * (aNum - bNum);
            }

            // 默认字符串比较
            const aVal = aCols[columnIndex] || '';
            const bVal = bCols[columnIndex] || '';
            return sortDirection * aVal.localeCompare(bVal);
        });

        // 重新渲染表格和分页
        renderTable();
        renderPagination();
    }

    // 渲染分页
    function renderPagination() {
        const pagination = document.getElementById('pagination');
        pagination.innerHTML = '';

        if (filteredData.length === 0) return;

        const totalPages = Math.ceil(filteredData.length / itemsPerPage);
        const startRecord = (currentPage - 1) * itemsPerPage + 1;
        const endRecord = Math.min(currentPage * itemsPerPage, filteredData.length);

        // 上一页按钮
        const prevBtn = document.createElement('button');
        prevBtn.className = 'page-btn';
        prevBtn.innerHTML = '<i class="fas fa-chevron-left"></i>';
        prevBtn.disabled = currentPage === 1;
        prevBtn.onclick = () => {
            if (currentPage > 1) {
                currentPage--;
                renderTable();
                renderPagination();
                window.scrollTo(0, 0);
            }
        };
        pagination.appendChild(prevBtn);

        // 页码按钮
        const maxVisiblePages = 5;
        let startPage = Math.max(1, currentPage - Math.floor(maxVisiblePages / 2));
        let endPage = Math.min(totalPages, startPage + maxVisiblePages - 1);

        if (endPage - startPage + 1 < maxVisiblePages) {
            startPage = Math.max(1, endPage - maxVisiblePages + 1);
        }

        if (startPage > 1) {
            const firstBtn = document.createElement('button');
            firstBtn.className = 'page-btn';
            firstBtn.textContent = '1';
            firstBtn.onclick = () => {
                currentPage = 1;
                renderTable();
                renderPagination();
                window.scrollTo(0, 0);
            };
            pagination.appendChild(firstBtn);

            if (startPage > 2) {
                const dots = document.createElement('span');
                dots.textContent = '...';
                dots.style.padding = '0 5px';
                pagination.appendChild(dots);
            }
        }

        for (let i = startPage; i <= endPage; i++) {
            const pageBtn = document.createElement('button');
            pageBtn.className = 'page-btn' + (i === currentPage ? ' active' : '');
            pageBtn.textContent = i;
            pageBtn.onclick = () => {
                currentPage = i;
                renderTable();
                renderPagination();
                window.scrollTo(0, 0);
            };
            pagination.appendChild(pageBtn);
        }

        if (endPage < totalPages) {
            if (endPage < totalPages - 1) {
                const dots = document.createElement('span');
                dots.textContent = '...';
                dots.style.padding = '0 5px';
                pagination.appendChild(dots);
            }

            const lastBtn = document.createElement('button');
            lastBtn.className = 'page-btn';
            lastBtn.textContent = totalPages;
            lastBtn.onclick = () => {
                currentPage = totalPages;
                renderTable();
                renderPagination();
                window.scrollTo(0, 0);
            };
            pagination.appendChild(lastBtn);
        }

        // 下一页按钮
        const nextBtn = document.createElement('button');
        nextBtn.className = 'page-btn';
        nextBtn.innerHTML = '<i class="fas fa-chevron-right"></i>';
        nextBtn.disabled = currentPage === totalPages;
        nextBtn.onclick = () => {
            if (currentPage < totalPages) {
                currentPage++;
                renderTable();
                renderPagination();
                window.scrollTo(0, 0);
            }
        };
        pagination.appendChild(nextBtn);

        // 页面信息
        const pageInfo = document.createElement('div');
        pageInfo.className = 'page-info';
        pageInfo.textContent = `显示 ${startRecord}-${endRecord} 条，共 ${filteredData.length} 条记录`;
        pagination.appendChild(pageInfo);
    }

    // 显示/隐藏加载指示器
    function showLoading(show) {
        document.getElementById('loadingIndicator').style.display = show ? 'flex' : 'none';
    }

    // 清除选择
    function clearSelection() {
        const checkboxes = document.querySelectorAll('#dataTable input[type="checkbox"]:not(#selectAll)');
        checkboxes.forEach(checkbox => {
            checkbox.checked = false;
            checkbox.closest('tr').classList.remove('highlighted');
        });

        document.getElementById('selectAll').checked = false;
        document.getElementById('selectAll').indeterminate = false;

        selectedKeys = [];
        saveSelectedRows(currentFileName, selectedKeys);
        showNotification('已清除所有选择', 'info');
    }

    // 切换高级筛选面板
    function toggleAdvancedFilter() {
        const filterPanel = document.getElementById('advancedFilter');
        filterPanel.classList.toggle('show');
    }

    // 应用高级筛选
    function applyAdvancedFilter() {
        const typeFilter = document.getElementById('filterType').value;
        const erpCodeFilter = document.getElementById('filterErpCode').value.toLowerCase();
        const partNoFilter = document.getElementById('filterPartNo').value.toLowerCase();
        const dateFromFilter = document.getElementById('filterDateFrom').value;
        const dateToFilter = document.getElementById('filterDateTo').value;

        // 重置为原始数据
        filteredData = [...allData];

        // 应用筛选
        filteredData = filteredData.filter(line => {
            const cols = line.split('|');

            // 类型筛选
            if (typeFilter && cols[1] !== typeFilter) {
                return false;
            }

            // ERP编码筛选
            if (erpCodeFilter && !cols[2].toLowerCase().includes(erpCodeFilter)) {
                return false;
            }

            // 部件编号筛选
            if (partNoFilter && !cols[3].toLowerCase().includes(partNoFilter)) {
                return false;
            }

            // 日期筛选
            const dateStr = cols[cols.length - 1];
            const date = new Date(dateStr);

            if (dateFromFilter && date < new Date(dateFromFilter)) {
                return false;
            }

            if (dateToFilter) {
                const toDate = new Date(dateToFilter);
                toDate.setHours(23, 59, 59); // 设置为结束时间
                if (date > toDate) {
                    return false;
                }
            }

            return true;
        });

        // 重置分页并重新渲染
        currentPage = 1;
        renderTable();
        renderPagination();

        showNotification(`筛选结果: ${filteredData.length} 条记录`, 'info');
    }

    // 重置高级筛选
    function resetAdvancedFilter() {
        document.getElementById('filterType').value = '';
        document.getElementById('filterErpCode').value = '';
        document.getElementById('filterPartNo').value = '';
        document.getElementById('filterDateFrom').value = '';
        document.getElementById('filterDateTo').value = '';

        // 重置为原始数据
        filteredData = [...allData];

        // 重置分页并重新渲染
        currentPage = 1;
        renderTable();
        renderPagination();

        showNotification('已重置筛选条件', 'info');
    }

    // 导出选中
    function exportSelected() {
        if (selectedKeys.length === 0) {
            showNotification('请先选择要导出的记录', 'warning');
            return;
        }

        // 显示导出选项模态框
        document.getElementById('exportModal').style.display = 'block';
    }

    // 确认导出
    function confirmExport() {
        const format = document.getElementById('exportFormat').value;
        const exportAllColumns = document.getElementById('exportAllColumns').checked;
        const exportSelectedOnly = document.getElementById('exportSelectedOnly').checked;

        closeExportModal();

        if (format === 'csv') {
            exportToCSV(exportAllColumns, exportSelectedOnly);
        } else if (format === 'excel') {
            exportToExcel(exportAllColumns, exportSelectedOnly);
        } else if (format === 'json') {
            exportToJSON(exportSelectedOnly);
        }
    }

    // 导出为CSV
    function exportToCSV(exportAllColumns, exportSelectedOnly) {
        // 构建CSV内容
        let csvContent = "文件名,类型,ERP编码,部件编号,类产品组,产品组,子产品组,部件名称1,类型号码,技术参数,描述,扫描时间\n";

        const dataToExport = exportSelectedOnly ?
            filteredData.filter(line => {
                const cols = line.split('|');
                const rowKey = cols[2] + '_' + cols[3];
                return selectedKeys.includes(rowKey);
            }) :
            filteredData;

        dataToExport.forEach(line => {
            const cols = line.split('|');

            // 转换类型字段
            const type = cols[1] === 'backup' ? '成功' : (cols[1] === 'error' ? '失败' : cols[1]);
            // 转换时间字段
            const time = formatToChineseDatetime(cols[cols.length - 1]);

            const row = [
                cols[0],
                type,
                cols[2],
                cols[3],
                cols[4],
                cols[5],
                cols[6],
                cols[7],
                cols[8],
                cols[9],
                cols[10],
                time
            ];

            csvContent += row.map(field => `"${field}"`).join(',') + '\n';
        });

        // 创建下载链接
        const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
        const url = URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.setAttribute('href', url);
        link.setAttribute('download', `合并日志_${new Date().toISOString().slice(0, 10)}.csv`);
        link.style.visibility = 'hidden';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);

        showNotification(`已导出 ${dataToExport.length} 条记录为CSV格式`, 'success');
    }

    // 导出为Excel
    function exportToExcel(exportAllColumns, exportSelectedOnly) {
        try {
            // 检查是否加载了XLSX库
            if (typeof XLSX === 'undefined') {
                showNotification('Excel导出库未加载，请刷新页面重试', 'error');
                return;
            }

            // 准备数据
            const dataToExport = exportSelectedOnly ?
                filteredData.filter(line => {
                    const cols = line.split('|');
                    const rowKey = cols[2] + '_'+ cols[3];
                    return selectedKeys.includes(rowKey);
                }) :
                filteredData;

            if (dataToExport.length === 0) {
                showNotification('没有数据可导出', 'warning');
                return;
            }

            // 构建Excel数据
            const excelData = dataToExport.map(line => {
                const cols = line.split('|');
                
                // 转换类型字段
                const type = cols[1] === 'backup' ? '成功' : (cols[1] === 'error' ? '失败' : cols[1]);
                // 转换时间字段
                const time = formatToChineseDatetime(cols[cols.length - 1]);

                return {
                    '文件名': cols[0] || '',
                    '类型': type,
                    'ERP编码': cols[2] || '',
                    '部件编号': cols[3] || '',
                    '类产品组': cols[4] || '',
                    '产品组': cols[5] || '',
                    '子产品组': cols[6] || '',
                    '部件名称1': cols[7] || '',
                    '类型号码': cols[8] || '',
                    '技术参数': cols[9] || '',
                    '描述': cols[10] || '',
                    '扫描时间': time
                };
            });

            // 创建工作簿
            const wb = XLSX.utils.book_new();
            
            // 创建工作表
            const ws = XLSX.utils.json_to_sheet(excelData);

            // 设置列宽
            const colWidths = [
                { wch: 20 }, // 文件名
                { wch: 8 },  // 类型
                { wch: 15 }, // ERP编码
                { wch: 15 }, // 部件编号
                { wch: 15 }, // 类产品组
                { wch: 15 }, // 产品组
                { wch: 15 }, // 子产品组
                { wch: 25 }, // 部件名称1
                { wch: 15 }, // 类型号码
                { wch: 30 }, // 技术参数
                { wch: 30 }, // 描述
                { wch: 20 }  // 扫描时间
            ];
            ws['!cols'] = colWidths;

            // 添加工作表到工作簿
            XLSX.utils.book_append_sheet(wb, ws, "PLM合并日志数据");

            // 生成文件名
            const fileName = `PLM合并日志_${new Date().toISOString().slice(0, 10)}.xlsx`;

            // 导出文件
            XLSX.writeFile(wb, fileName);

            showNotification(`成功导出 ${excelData.length} 条记录为Excel格式`, 'success');

        } catch (error) {
            console.error('Excel export error:', error);
            showNotification('Excel导出失败: ' + error.message, 'error');
        }
    }

    // 导出为JSON
    function exportToJSON(exportSelectedOnly) {
        const dataToExport = exportSelectedOnly ?
            filteredData.filter(line => {
                const cols = line.split('|');
                const rowKey = cols[2] + '_' + cols[3];
                return selectedKeys.includes(rowKey);
            }) :
            filteredData;

        const jsonData = dataToExport.map(line => {
            const cols = line.split('|');
            return {
                fileName: cols[0],
                type: cols[1],
                erpCode: cols[2],
                partNo: cols[3],
                productClassGroup: cols[4],
                productGroup: cols[5],
                subProductGroup: cols[6],
                partName1: cols[7],
                typeNumber: cols[8],
                technicalParams: cols[9],
                description: cols[10],
                scanTime: cols[11]
            };
        });

        const jsonStr = JSON.stringify(jsonData, null, 2);
        const blob = new Blob([jsonStr], { type: 'application/json;charset=utf-8;' });
        const url = URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.setAttribute('href', url);
        link.setAttribute('download', `合并日志_${new Date().toISOString().slice(0, 10)}.json`);
        link.style.visibility = 'hidden';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);

        showNotification(`已导出 ${dataToExport.length} 条记录为JSON格式`, 'success');
    }

    // 关闭导出模态框
    function closeExportModal() {
        document.getElementById('exportModal').style.display = 'none';
    }

    // 显示详情模态框
    function showDetail(index) {
        const line = filteredData[index];
        const cols = line.split('|');

        // 转换类型字段
        const type = cols[1] === 'backup' ? '成功' : (cols[1] === 'error' ? '失败' : cols[1]);

        // 转换时间字段
        const time = formatToChineseDatetime(cols[cols.length - 1]);

        const detailContent = document.getElementById('detailContent');
        detailContent.innerHTML = `
                <div class="form-group">
                    <label>文件名</label>
                    <input type="text" class="form-control" value="${cols[0]}" readonly>
                </div>
                <div class="form-group">
                    <label>类型</label>
                    <input type="text" class="form-control" value="${type}" readonly>
                </div>
                <div class="form-group">
                    <label>ERP编码</label>
                    <input type="text" class="form-control" value="${cols[2]}" readonly>
                </div>
                <div class="form-group">
                    <label>部件编号</label>
                    <input type="text" class="form-control" value="${cols[3]}" readonly>
                </div>
                <div class="form-group">
                    <label>类产品组</label>
                    <input type="text" class="form-control" value="${cols[4]}" readonly>
                </div>
                <div class="form-group">
                    <label>产品组</label>
                    <input type="text" class="form-control" value="${cols[5]}" readonly>
                </div>
                <div class="form-group">
                    <label>子产品组</label>
                    <input type="text" class="form-control" value="${cols[6]}" readonly>
                </div>
                <div class="form-group">
                    <label>部件名称1</label>
                    <input type="text" class="form-control" value="${cols[7]}" readonly>
                </div>
                <div class="form-group">
                    <label>类型号码</label>
                    <input type="text" class="form-control" value="${cols[8]}" readonly>
                </div>
                <div class="form-group">
                    <label>技术参数</label>
                    <input type="text" class="form-control" value="${cols[9]}" readonly>
                </div>
                <div class="form-group">
                    <label>描述</label>
                    <input type="text" class="form-control" value="${cols[10]}" readonly>
                </div>
                <div class="form-group">
                    <label>扫描时间</label>
                    <input type="text" class="form-control" value="${time}" readonly>
                </div>
            `;

        document.getElementById('detailModal').style.display = 'block';
    }

    // 关闭详情模态框
    function closeDetailModal() {
        document.getElementById('detailModal').style.display = 'none';
    }

    // 点击模态框外部关闭
    window.onclick = function(event) {
        const detailModal = document.getElementById('detailModal');
        const exportModal = document.getElementById('exportModal');

        if (event.target === detailModal) {
            closeDetailModal();
        }

        if (event.target === exportModal) {
            closeExportModal();
        }
    };
</script>
</body>
</html>